import 'package:flutter/material.dart';
import 'package:habit_master/core/models/habit.dart';

class HabitCreationScreen extends StatefulWidget {
  const HabitCreationScreen({Key? key}) : super(key: key);

  @override
  _HabitCreationScreenState createState() => _HabitCreationScreenState();
}

class _HabitCreationScreenState extends State<HabitCreationScreen> {
  final _formKey = GlobalKey<FormState>();
  
  // 表单数据
  String _title = '';
  IconData _selectedIcon = Icons.directions_run;
  HabitFrequency _frequency = HabitFrequency.daily;
  List<int> _selectedDays = [0, 1, 2, 3, 4]; // 默认工作日
  TimeOfDay _reminderTime = const TimeOfDay(hour: 8, minute: 0);
  
  // 四步习惯养成法
  String _cue = '';
  String _craving = '';
  String _response = '';
  String _reward = '';

  // 可选图标列表
  final List<IconData> _icons = [
    Icons.directions_run,
    Icons.book,
    Icons.local_drink,
    Icons.apple,
    Icons.nightlight_round,
    Icons.fitness_center,
    Icons.edit,
    Icons.spa,
    Icons.self_improvement,
    Icons.music_note,
    Icons.code,
    Icons.brush,
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('添加新习惯'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(20),
          children: [
            _buildTitleField(),
            const SizedBox(height: 20),
            _buildIconSelector(),
            const SizedBox(height: 20),
            _buildFrequencySelector(),
            if (_frequency == HabitFrequency.custom) 
              _buildCustomDaysSelector(),
            const SizedBox(height: 20),
            _buildTimeSelector(),
            const SizedBox(height: 20),
            _buildTheorySection(),
            const SizedBox(height: 30),
            const Text(
              '四步习惯养成法',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 20),
            _buildCueField(),
            const SizedBox(height: 20),
            _buildCravingField(),
            const SizedBox(height: 20),
            _buildResponseField(),
            const SizedBox(height: 20),
            _buildRewardField(),
            const SizedBox(height: 30),
          ],
        ),
      ),
      bottomNavigationBar: _buildBottomActions(),
    );
  }
  
  Widget _buildTitleField() {
    return TextFormField(
      decoration: const InputDecoration(
        labelText: '习惯名称',
        hintText: '例如：晨跑5公里',
      ),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return '请输入习惯名称';
        }
        return null;
      },
      onChanged: (value) {
        setState(() {
          _title = value;
        });
      },
    );
  }
  
  Widget _buildIconSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '选择图标',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 10),
        Wrap(
          spacing: 15,
          runSpacing: 15,
          children: _icons.map((icon) {
            final isSelected = _selectedIcon == icon;
            return GestureDetector(
              onTap: () {
                setState(() {
                  _selectedIcon = icon;
                });
              },
              child: Container(
                width: 50,
                height: 50,
                decoration: BoxDecoration(
                  color: isSelected 
                      ? const Color(0xFFC8E6C9) 
                      : const Color(0xFFE8F5E9),
                  borderRadius: BorderRadius.circular(25),
                  border: isSelected
                      ? Border.all(
                          color: const Color(0xFF4CAF50),
                          width: 2,
                        )
                      : null,
                ),
                child: Icon(
                  icon,
                  color: const Color(0xFF4CAF50),
                  size: 24,
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }
  
  Widget _buildFrequencySelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '频率',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 10),
        Wrap(
          spacing: 10,
          runSpacing: 10,
          children: [
            _buildFrequencyOption(HabitFrequency.daily, '每天'),
            _buildFrequencyOption(HabitFrequency.weekdays, '工作日'),
            _buildFrequencyOption(HabitFrequency.weekends, '周末'),
            _buildFrequencyOption(HabitFrequency.custom, '自定义'),
          ],
        ),
      ],
    );
  }
  
  Widget _buildFrequencyOption(HabitFrequency frequency, String label) {
    final isSelected = _frequency == frequency;
    return GestureDetector(
      onTap: () {
        setState(() {
          _frequency = frequency;
          // 根据频率设置默认选中的日期
          switch (frequency) {
            case HabitFrequency.daily:
              _selectedDays = [0, 1, 2, 3, 4, 5, 6];
              break;
            case HabitFrequency.weekdays:
              _selectedDays = [0, 1, 2, 3, 4];
              break;
            case HabitFrequency.weekends:
              _selectedDays = [5, 6];
              break;
            case HabitFrequency.custom:
              // 保持现有选择
              break;
          }
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: 15,
          vertical: 10,
        ),
        decoration: BoxDecoration(
          color: isSelected 
              ? const Color(0xFF4CAF50) 
              : const Color(0xFFF2F2F2),
          borderRadius: BorderRadius.circular(20),
        ),
        child: Text(
          label,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.black87,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          ),
        ),
      ),
    );
  }
  
  Widget _buildCustomDaysSelector() {
    final days = ['一', '二', '三', '四', '五', '六', '日'];
    
    return Padding(
      padding: const EdgeInsets.only(top: 15),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: List.generate(7, (index) {
          final isSelected = _selectedDays.contains(index);
          return GestureDetector(
            onTap: () {
              setState(() {
                if (isSelected) {
                  _selectedDays.remove(index);
                } else {
                  _selectedDays.add(index);
                }
              });
            },
            child: Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: isSelected 
                    ? const Color(0xFF4CAF50) 
                    : Colors.transparent,
                border: Border.all(
                  color: isSelected 
                      ? const Color(0xFF4CAF50) 
                      : Colors.grey,
                ),
                borderRadius: BorderRadius.circular(20),
              ),
              alignment: Alignment.center,
              child: Text(
                days[index],
                style: TextStyle(
                  color: isSelected ? Colors.white : Colors.black87,
                ),
              ),
            ),
          );
        }),
      ),
    );
  }
  
  Widget _buildTimeSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '提醒时间',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 10),
        Text(
          '${_reminderTime.hour}:${_reminderTime.minute}',
          style: const TextStyle(
            fontSize: 14,
            color: Colors.grey,
          ),
        ),
        const SizedBox(height: 10),
        TextButton(
          onPressed: () {
            showTimePicker(
              context: context,
              initialTime: _reminderTime,
            ).then((value) {
              if (value != null) {
                setState(() {
                  _reminderTime = value;
                });
              }
            });
          },
          child: const Text('选择时间'),
        ),
      ],
    );
  }
  
  Widget _buildTheorySection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: const [
        Text(
          '四步习惯养成法',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(height: 10),
        Text(
          '四步习惯养成法是一种有效的习惯养成方法，它包括以下四个步骤：',
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey,
          ),
        ),
      ],
    );
  }
  
  Widget _buildCueField() {
    return TextFormField(
      decoration: const InputDecoration(
        labelText: '明显的提示',
        hintText: '例如：看到咖啡杯',
      ),
      onChanged: (value) {
        setState(() {
          _cue = value;
        });
      },
    );
  }
  
  Widget _buildCravingField() {
    return TextFormField(
      decoration: const InputDecoration(
        labelText: '强烈的渴望',
        hintText: '例如：想喝咖啡',
      ),
      onChanged: (value) {
        setState(() {
          _craving = value;
        });
      },
    );
  }
  
  Widget _buildResponseField() {
    return TextFormField(
      decoration: const InputDecoration(
        labelText: '简单的行动',
        hintText: '例如：喝一杯咖啡',
      ),
      onChanged: (value) {
        setState(() {
          _response = value;
        });
      },
    );
  }
  
  Widget _buildRewardField() {
    return TextFormField(
      decoration: const InputDecoration(
        labelText: '满意的奖励',
        hintText: '例如：享受咖啡的美味',
      ),
      onChanged: (value) {
        setState(() {
          _reward = value;
        });
      },
    );
  }
  
  Widget _buildBottomActions() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: () {
            if (_formKey.currentState!.validate()) {
              // 表单验证通过，处理表单数据
            }
          },
          child: const Text('保存'),
        ),
      ],
    );
  }
}
